# coding: utf-8
import urllib
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
import time
from Tkinter import *

url='http://flight.qunar.com/site/oneway_list.htm?'

class Route:
    def __init__(self, departureAirport, arrivalAirport, departureTime):
        self.departureAirport = departureAirport
        self.arrivalAirport = arrivalAirport
        self.departureTime = departureTime
    
    def generateLink(self):
        params = urllib.urlencode({'searchDepartureAirport': self.departureAirport, 
                           'searchArrivalAirport': self.arrivalAirport, 
                           'searchDepartureTime': self.departureTime,
                           'searchType': 'OneWayFlight',
                           })
        return url + params
    
    def rountDesc(self):
        return '%s to %s on %s' % (self.departureAirport.decode('utf-8'), self.arrivalAirport.decode('utf-8'), self.departureTime)
        

if __name__=='__main__':
    browser = webdriver.Firefox()
    routeList = []
    routeList.append(Route('成都','上海','2011-10-07'))
    routeList.append(Route('成都','南京','2011-10-07'))
    routeList.append(Route('成都','无锡','2011-10-07'))
    routeList.append(Route('重庆','上海','2011-10-07'))
    routeList.append(Route('重庆','南京','2011-10-07'))
    routeList.append(Route('重庆','无锡','2011-10-07'))
    
    routeList.append(Route('上海','西宁','2011-09-16'))
    routeList.append(Route('上海','西宁','2011-09-17'))
    
    route_len = len(routeList)
    i=0
    while True:
        j = i % route_len
        route = routeList[j]
        browser.get(route.generateLink())
        time.sleep(60)
        datebar = browser.find_elements_by_class_name('cur')
        
        if len(datebar) == 1:
            datebar1 = datebar[0]

            curDate = datebar1.find_elements_by_class_name('pr')    
            curDate1 = curDate[0]
            curPrice = curDate1.text[1:]
            curTime = time.strftime("%H:%M:%S %b,%d %Y", time.localtime())
            print curTime + ' ' + curPrice + ' ' + route.rountDesc()
            if int(curPrice) < 600:     

                root.title('Air Price Killing')
                root.geometry('300x200+100+100')
                w1 = Label(root, text= price + '\n' + curTime) 
                w1.pack()
                w2 = Label(root, text= 'Ivan Wang' + '\n' + '0.1Beta') 
                w2.pack(side=RIGHT)
                root.mainloop()
                browser.quit()

                break
        else:
            print ("Open Error!")
        time.sleep(30)
        i=i+1

